#!/usr/bin/perl
#
# Change password for a counter administrator
#
use Counter::CGI;
use CGI::Carp;
use Apache::Htpasswd;
use CounterCGI;

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8

$q = new Counter::CGI;

$oldpass = $q->param("oldpass");
$newpass = $q->param("newpass1");
if (!$oldpass) { error(__("Old password not given")); }
if (!$newpass) { error(__("New password not given")); }

if ($q->param("newpass2") ne $newpass) {
    error(__("Password mismatch"));
}
if (!$ENV{REMOTE_USER}) {
    error(__("Not logged in"));
}

# warn "Changing password for $ENV{REMOTE_USER} from $oldpass to $newpass\n"; 
$pwf = new Apache::Htpasswd("$ENV{COUNTER_ROOT}/access/users");
$pwf->htpasswd($ENV{REMOTE_USER}, $newpass, $oldpass)
    || error(__("Change password failed"));


print $q->redirect("/adm/");

sub error {

    my $msg = shift;

print "Content-type: text/html; charset=\"utf-8\"\n";
print "\n";
print "<html>\n<head>\n<title>", __("Password error"), "</title>\n";
print "</head>\n<body>\n";
print "<h1>", __("Error in password change"), "</h1>\n";
print __("The error was"), ": $msg";
print <<EoF;
</body>
</html>
EoF
    exit(0);

}
